package finbudgettable.client.ui.grid.cell.status;

import com.google.gwt.cell.client.Cell;

import finbudget.client.ui.table.Record;
import finbudgettable.client.ui.grid.CellGrid;
import finbudgettable.client.ui.grid.column.GridColumn;
import finbudgettable.client.ui.grid.event.RecordChangedEvent;
import finbudgettable.client.ui.grid.event.RecordChangedHandler;

public class StatusColumn extends GridColumn<Record> {

    public static final String FIELD_NAME = "@status";

	protected StatusColumn(Builder builder) {
		super(builder);
	}

	@Override
	protected boolean isValueChanged(Record record, Record value) {
		RecordStatus original = StatusCell.getRecordStatus(record);
		RecordStatus last = StatusCell.getRecordStatus(value);
		return original == last;
	}

	@Override
	public Record getValue(Record object) {
		return object;
	}

    @Override
    public boolean canBeHidden() {
        return false;
    }

    @Override
    protected String getCellStyleNames() {
        return StatusCell.RESOURCES.style().bStatusCell();
    }

    public static class Builder extends GridColumn.Builder<StatusCell, Record> {

		public Builder(CellGrid grid, boolean hasTotals) {
			super(grid, FIELD_NAME, hasTotals);
            setResizable(false);
            setDraggable(false);
            setColumnMenu(null);
            setSortable(false);
            setWidth("21px");
		}

		@Override
		protected StatusCell createCell() {
			return new StatusCell(grid);
		}

		@Override
		protected GridColumn<Record> createColumn(Cell<Record> cell) {
			return new StatusColumn(this);
		}

		@Override
        public GridColumn<Record> build() {
            GridColumn<Record> column = super.build();
            grid.addHandler(new RecordChangedHandler() {
                @Override
                public void onRecordChanged(RecordChangedEvent event) {
                    grid.refreshCell(event.getRecord(), FIELD_NAME);
                }
            }, RecordChangedEvent.TYPE);
            return column;
        }
    }

}
